var User = require('User').User;

/**
 * public
 * 排行榜列表，所有的好友排行榜均在此
 * @param openid
 * @param names
 * @constructor
 */
function RankList(openid,names) {
    this.openid = openid;
    this.user = null;
    this.users = {};
    this.isLoading = false;
    this.isComplete = false;
    this.names = names;
    this.loadBackList = [];
    this.ranks = {};
    this.load();
}

/**
 * public
 * 加载排行榜
 * @param back 回调函数，加载完成后调用，如果已经加载完成，则立即调用
 */
RankList.prototype.load = function (back) {
    if(this.isComplete) {
        if(back) back();
    } else if(!this.isLoading) {
        this.loadBackList.push(back);
        this.loadRank();
    } else {
        this.loadBackList.push(back);
    }
}

/**
 * private
 * 加载排行榜
 */
RankList.prototype.loadRank = function () {
    this.isLoading = true;
    wx.getUserInfo({
        openIdList: [this.openid],
        success: result =>{
            this.user = this.createUser(result.data[0]);
            wx.getFriendCloudStorage({
                keyList: this.names,
                success: res => {
                    let data = res.data;
                    for(let n = 0; n < this.names.length; n++) {
                        let list = this.ranks[this.names[n]] = [];
                        let findMy = false;
                        for(let i = 0; i < data.length; i++) {
                            let value = this.getKVRankValue(this.names[n],data[i]);
                            if(value >= 0) {
                                list.push(new Rank(this.createUser(data[i]),value));
                                if(list[list.length-1].user.openid == this.openid) {
                                    findMy = true;
                                }
                            }
                        }
                        if(!findMy) {
                            list.push(new Rank(this.user,0,true));
                        }
                        this.sort(this.names[n]);
                    }
                    this.loadComplete();
                }
            })
        }
    });
}

RankList.prototype.loadRankGroup = function () {
    this.isLoading = true;
    wx.getUserInfo({
        openIdList: [this.openid],
        success: result =>{
            this.user = this.createUser(result.data[0]);
            wx.getGroupCloudStorage({
                shareTicket: ticket,  // 需要带上shareTicket
                keyList: ['score', 'maxScore'],
                success: res => {
                    console.log(res.data+"===============---------");
                },
                fail: res => {
                    console.log(res.data+"---------------=========");
                }
            });
        }
    });
}

/**
 * 创建用户信息
 * @param data
 * @returns {*|User}
 */
RankList.prototype.createUser = function(data) {
    let openid = data.openid || data.openId;
    return this.users[openid] || (this.users[openid] = new User(data));
}

/**
 * private
 * 加载完成
 */
RankList.prototype.loadComplete = function() {
    this.isLoading = false;
    this.isComplete = true;
    for(let i = 0; i < this.loadBackList.length; i++) {
        if(this.loadBackList[i]) this.loadBackList[i]();
    }
    this.loadBackList = null;
    console.log(this.ranks);
}

/**
 * private
 * @param name
 * @param data
 * @param createScore
 * @returns {number}
 */
RankList.prototype.getKVRankValue = function(name="rank",data=null,createScore=false) {
    let value = createScore ? 0 : -1;
    if(data && data.KVDataList) {
        for(let j = 0; j < data.KVDataList.length; j++) {
            if(data.KVDataList[j].key == name) {
                value = parseInt(data.KVDataList[j].value);
            }
        }
    }
    return value;
}

/**
 * 获取排行榜的长度
 * @param name
 */
RankList.prototype.getLength = function(name="rank") {
    return this.ranks[name] ? this.ranks[name].length : 0;
}

/**
 * 排列
 * @param smallToBig true 从低到高排列，false 从高到低排列
 */
RankList.prototype.sort = function(name="rank",smallToBig = false) {
    let list = this.ranks[name];
    for(let i = 0, len = list.length; i < len - 1; i++) {
        if(smallToBig) {
            if(list[i].value > list[i + 1].value) {
                let c = list[i + 1];
                list[i + 1] = list[i];
                list[i] = c;
                i = -1;
            }
        } else {
            if(list[i].value < list[i + 1].value) {
                let c = list[i + 1];
                list[i + 1] = list[i];
                list[i] = c;
                i = -1;
            }
        }
    }
}

/**
 * 获取排名中第几个
 * @param name
 * @param index
 * @returns {*}
 */
RankList.prototype.getAt = function(name="rank",index=0) {
    if(!this.ranks[name]) return null;
    if(index < 0) return null;
    if(index >= this.ranks[name].length) return null;
    return this.ranks[name][index];
}

RankList.prototype.getRankIndex = function(name="rank",openid="") {
    let list = this.ranks[name];
    for(let i = 0; i < list.length; i++) {
        if(list[i].user.openid == openid) return i;
    }
    return -1;
}

/**
 * public
 * 前提是从低到高排列
 * @param name
 * @param value
 * @returns {number}
 */
RankList.prototype.getValueBiggerRank = function(name="rank",value=0) {
    let list = this.ranks[name];
    for(let i = 0; i < list.length; i++) {
        if(list[i].value > value && list[i].user.openid != this.openid) {
            return list[i];
        }
    }
    return null;
}

/**
 * 上传分数
 * @param name 排行榜名称
 * @param score 分数
 */
RankList.prototype.upLoad = function (name="rank",score) {
    console.log("上传分数:" + name + ":" + score);
}

/**
 * private
 * @param names
 * @param data
 * @constructor
 */
function Rank(user,value) {
    this.user = user;
    this.value = value;
}

exports.RankList = RankList;